import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 统一数据同步API
export const unifiedAPI = {
  // 获取店铺数据（根据用户角色）
  getStores(userId) {
    return api.get('/unified/stores', { params: { userId } })
  },
  
  // 获取用户信息
  getUserInfo(userId) {
    return api.get('/unified/user-info', { params: { userId } })
  },
  
  // 检查权限
  checkPermission(userId, resource, action) {
    return api.get('/unified/check-permission', { 
      params: { userId, resource, action } 
    })
  }
}

// 认证API
export const authAPI = {
  login(data) {
    return api.post('/auth/login', data)
  },
  
  register(data) {
    return api.post('/auth/register', data)
  },
  
  getUserInfo(userId) {
    return api.get('/auth/user-info', { params: { userId } })
  }
}

// 店铺API
export const storeAPI = {
  getStores() {
    return api.get('/stores')
  },
  
  getStoreById(id) {
    return api.get(`/stores/${id}`)
  },
  
  createStore(data) {
    return api.post('/stores', data)
  },
  
  updateStore(id, data) {
    return api.put(`/stores/${id}`, data)
  },
  
  deleteStore(id) {
    return api.delete(`/stores/${id}`)
  }
}

// 商品API
export const productAPI = {
  getProducts() {
    return api.get('/products')
  },
  
  getProductById(id) {
    return api.get(`/products/${id}`)
  },
  
  createProduct(data) {
    return api.post('/products', data)
  },
  
  updateProduct(id, data) {
    return api.put(`/products/${id}`, data)
  },
  
  deleteProduct(id) {
    return api.delete(`/products/${id}`)
  }
}

// 订单API
export const orderAPI = {
  getOrders() {
    return api.get('/orders')
  },
  
  getOrderById(id) {
    return api.get(`/orders/${id}`)
  },
  
  updateOrder(id, data) {
    return api.put(`/orders/${id}`, data)
  }
}

// WebSocket连接管理器
export class DataSyncManager {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.listeners = new Map()
  }
  
  connect(userId, role) {
    try {
      this.ws = new WebSocket(`ws://localhost:8080/websocket/${userId}/${role}`)
      
      this.ws.onopen = () => {
        console.log('WebSocket连接成功')
        this.reconnectAttempts = 0
      }
      
      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          this.handleMessage(data)
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
        }
      }
      
      this.ws.onclose = () => {
        console.log('WebSocket连接关闭')
        this.reconnect(userId, role)
      }
      
      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
      }
      
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.reconnect(userId, role)
    }
  }
  
  handleMessage(data) {
    const { type, dataType, operation } = data
    
    switch (type) {
      case 'connection':
        console.log('WebSocket连接状态:', data.status)
        break
        
      case 'dataUpdate':
        console.log('数据更新:', dataType, operation, data.data)
        this.notifyListeners(dataType, data)
        break
        
      case 'notification':
        console.log('收到通知:', data.data)
        this.notifyListeners('notification', data)
        break
        
      case 'broadcast':
        console.log('收到广播:', data.data)
        this.notifyListeners('broadcast', data)
        break
    }
  }
  
  reconnect(userId, role) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
      
      setTimeout(() => {
        this.connect(userId, role)
      }, this.reconnectInterval)
    } else {
      console.error('WebSocket重连失败，已达到最大重连次数')
    }
  }
  
  addListener(dataType, callback) {
    if (!this.listeners.has(dataType)) {
      this.listeners.set(dataType, [])
    }
    this.listeners.get(dataType).push(callback)
  }
  
  removeListener(dataType, callback) {
    if (this.listeners.has(dataType)) {
      const callbacks = this.listeners.get(dataType)
      const index = callbacks.indexOf(callback)
      if (index > -1) {
        callbacks.splice(index, 1)
      }
    }
  }
  
  notifyListeners(dataType, data) {
    if (this.listeners.has(dataType)) {
      this.listeners.get(dataType).forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('执行监听器回调失败:', error)
        }
      })
    }
  }
  
  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    this.listeners.clear()
    this.reconnectAttempts = 0
  }
}

export default api 